<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="站点名称" prop="siteName">
        <el-input v-model="queryParams.siteName" placeholder="请输入站点名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="站点联系人" prop="siteTelName">
        <el-input v-model="queryParams.siteTelName" placeholder="请输入站点联系人" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="站点类型" prop="siteType">
        <el-select v-model="queryParams.siteType" placeholder="请选择站点类型" clearable>
          <el-option v-for="dict in dict.type.site_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="站点联系地址" prop="siteAddress">
        <el-input
          v-model="queryParams.siteAddress"
          placeholder="请输入站点联系地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="站点状态" prop="siteState">
        <el-select v-model="queryParams.siteState" placeholder="请选择站点状态">
          <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['site:site:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['site:site:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['site:site:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['site:site:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siteList">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="站点id" align="center" prop="siteId" /> -->
      <el-table-column label="站点名称" align="center" prop="siteName" />
      <el-table-column label="站点联系人" align="center" prop="siteTelName" />
      <el-table-column label="站点联系电话" align="center" prop="siteTel" />
      <el-table-column label="站点类型" align="center" prop="siteType">
        <template v-slot:default="scope">
          <dict-tag :options="dict.type.site_type" :value="scope.row.siteType" />
        </template>
      </el-table-column>
      <el-table-column label="站点联系地址" align="center" prop="siteAddress" />
      <el-table-column label="站点状态" align="center" prop="siteState">
        <template v-slot:default="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.siteState" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot:default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['site:site:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['site:site:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改站点管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="35%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="站点名称" prop="siteName">
          <el-input v-model="form.siteName" placeholder="请输入站点名称" />
        </el-form-item>
        <el-form-item label="站点联系人" prop="siteTelName">
          <el-input v-model="form.siteTelName" placeholder="请输入站点联系人" />
        </el-form-item>
        <el-form-item label="站点联系电话" prop="siteTel">
          <el-input v-model="form.siteTel" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="站点类型" prop="siteType">
          <el-select v-model="form.siteType" style="width: 100%;" placeholder="请选择站点类型">
            <el-option v-for="dict in dict.type.site_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="站点联系地址" prop="siteAddress">
          <el-input v-model="form.siteAddress" placeholder="请输入站点联系地址" />
        </el-form-item>
        <el-form-item label="站点经纬度" prop="siteAddress">
          <!-- <el-input v-model="form.siteAddress" placeholder="请输入站点联系地址" /> -->
          <div style="background-color: rgba(192, 196, 204,0.3);display: flex;justify-content: space-between;">
            <div v-if="form.mapX" style="padding: 0 5px">{{ form.mapX }},{{ form.mapY }}</div>
            <div v-else style="padding: 0 5px;color: rgba(192, 196, 204,1)">请选择经纬度</div>
            <el-button type="primary" @click="mapFun">选择经纬度</el-button>
          </div>
        </el-form-item>
        <el-form-item label="站点状态" prop="siteState">
          <el-select v-model="form.siteState" style="width: 100%;" placeholder="请选择站点状态">
            <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="经纬度选择" :visible.sync="mapOpen" width="35%">
      <div>
        <div class="mapOpen_header">
          <div class="mapOpen_right">
            经纬度：{{ addForm.longlat }}
          </div>
          <div class="mapOpen_left">
            地址：{{ addForm.adress }}
          </div>
        </div>
        <div style="margin-bottom: 10px;">
          <el-select style="width: 100%;" v-model="addForm.name" filterable remote reserve-keyword placeholder="请输入关键词"
            :remote-method="placeSearch" @change="addFormChange">
            <el-option v-for="item in addFormOptions" :key="item.id" :label="item.cityname + item.adname + item.address"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        <div id="container" ref="amap"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMap">确 定</el-button>
        <el-button @click="mapOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { listSite, getSite, delSite, addSite, updateSite } from "@/api/site/site";
export default {
  name: "Site",
  dicts: ['site_type', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 站点管理表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        siteName: null,
        siteTelName: null,
        siteTel: null,
        siteType: null,
        siteAddress: null,
        siteState: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      mapOpen: false,
      map: '',
      smapBoll: false,
      geocoder: '',
      markers: [],
      markersPosition: undefined,
      lnglatLat: '',
      lnglatLng: '',
      districtLoader: '',
      addForm: {
        longlat: '',
        adress: '',
        name: ''
      },
      addFormOptions: []
    };
  },
  mounted() {
    this.initAMap();
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询站点管理列表 */
    getList() {
      this.loading = true;
      listSite(this.queryParams).then(response => {
        this.siteList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        siteId: null,
        siteName: null,
        siteTelName: null,
        siteTel: null,
        siteType: null,
        siteAddress: null,
        siteState: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.siteId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加站点管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const siteId = row.siteId || this.ids
      getSite(siteId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改站点管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.siteId != null) {
            updateSite(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSite(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const siteIds = row.siteId || this.ids;
      this.$modal.confirm('是否确认删除站点管理编号为"' + siteIds + '"的数据项？').then(function () {
        return delSite(siteIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('site/site/export', {
        ...this.queryParams
      }, `site_${new Date().getTime()}.xlsx`)
    },
    mapFun() {

      this.mapOpen = true
      this.smapBoll = false
      let _this = this
      setTimeout(() => {
        _this.initAMap()
      }, 100)


    },
    submitMap() {
      this.form.siteAddress = this.addForm.adress
      this.form.mapX = this.lnglatLng
      this.form.mapY = this.lnglatLat
      this.mapOpen = false

      console.log(this.lnglatLat, this.lnglatLng, 1243124124)
    },

    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "249fc67c47f2650bfeec222499e82c16",
      };
      AMapLoader.reset()
      let _this = this
      AMapLoader.load({
        key: '37ab382ecdb27440a23c0a28853e8c86', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '1.4.15', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder', 'AMap.PlaceSearch']  // 需要使用的的插件列表，如比例尺'AMap.Scale'等，如果是地图控件，必须再 map.addControl添加
      })
        .then((AMap) => {
          _this.map = new AMap.Map('container', {
            // 设置地图容器id
            zoom: 15, // 初始化地图级别
            // 可以设置初始化当前位置
            // center: [116.368904, 39.913423] // 初始化地图位置
          })
          _this.geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
          });

          _this.map.on("click", (e) => {
            console.log(e)
            this.lnglatLat = e.lnglat.lat;
            this.lnglatLng = e.lnglat.lng;
            this.addForm.longlat = `${this.lnglatLng},${this.lnglatLat}`;
            this.markersPosition = [e.lnglat.lng, e.lnglat.lat];
            // 点击坐标
            this.removeMarker();
            // 设置新的标记
            this.setMapMarker();
          });

          // _this.map = map
        })
        .catch((e) => {
          console.log(e)
        })
    },
    // 设置点击位置的标记
    setMapMarker() {
      let _this = this
      let marker = new AMap.Marker({
        map: this.map,
        position: this.markersPosition,
      });
      _this.map.setCenter(this.markersPosition);
      // 将 markers 添加到地图
      _this.markers.push(marker);
      _this.geocoder.getAddress(_this.markersPosition,
        function (status, result) {
          if (status === "complete" && result.info === "OK") {
            //详细地址
            _this.addForm.adress = result.regeocode.formattedAddress
          }
        })

    },
    // 地址搜索
    placeSearch(search) {
      if (search !== '') {
        let _this = this
        // let search = this.addForm.name
        if (!search) return;
        let placeSearch = new AMap.PlaceSearch({
          city: '信阳市', // 兴趣点城市，支持城市名、citycode、adcode
          citylimit: true, // 是否强制在设置的城市内搜索，默认false
          // type: '', // 兴趣点类别，用‘|’分隔，默认：'餐饮服务|商务住宅|生活服务'
          pageSize: 20, // 每页条数，默认10，范围1-50
          pageIndex: 1, // 页码
          extensions: 'all', // 默认base，返回基本地址信息；all：返回详细信息
          // map: map, // 地图实例，可选
          // panel: 'panel', // 结果列表的id容器，可选 
          autoFitView: true, // 是否自动调整地图视野到marker点都处于可见范围
        })
        placeSearch.search(search, function (status, result) {
          _this.addFormOptions = result.poiList.pois
        })

      } else {
        _this.addFormOptions = []
      }
    },

    addFormChange(e) {
      let parm = {}
      for (let item of this.addFormOptions) {
        if (item.id == e) {
          parm = item
        }
      }

      if (parm.id) {
        this.lnglatLat = parm.location.lat;
        this.lnglatLng = parm.location.lng;
        this.addForm.longlat = `${this.lnglatLng},${this.lnglatLat}`;
        this.markersPosition = [this.lnglatLng, this.lnglatLat];
        // 点击坐标
        this.removeMarker();
        // 设置新的标记
        this.setMapMarker();
      }

    },

    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
  }
};
</script>
<style scoped lang="scss">
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}

.mapOpen_header {
  padding: 10px 0;

  .mapOpen_left {}

  .mapOpen_right {}

}
</style>